package com.linktrip.devicemanager.control.device;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.google.gson.Gson;
import com.linktrip.devicemanager.entity.DeviceInfo;
import com.linktrip.devicemanager.server.DeviceService;
import com.linktrip.devicemanager.server.OfficeService;
import com.linktrip.devicemanager.util.CommandUtil;
import com.linktrip.devicemanager.util.Constant;
import com.linktrip.devicemanager.util.PageInfo;
import com.linktrip.devicemanager.util.ToolKits;

@Controller
@RequestMapping(value = "/service/device")
public class DeviceControl {
	Logger logger = LoggerFactory.getLogger(DeviceControl.class);
	@Autowired
	private DeviceService server;
	
	@Autowired
	private OfficeService officeService;

	@RequestMapping(value = "/addDevice.lt")
	@ResponseBody
	public String addDevice(HttpServletRequest request, HttpServletResponse response) {

		String deviceNo = ToolKits.getRequestParamValue(request, "device_no");
		String phoneNumber = ToolKits.getRequestParamValue(request, "phone_number");
		String simNo = ToolKits.getRequestParamValue(request, "sim_no");
		String deviceDesc = ToolKits.getRequestParamValue(request, "device_desc");

		DeviceInfo entity = new DeviceInfo(deviceNo, phoneNumber, simNo, deviceDesc);
		entity.setCreate_date(new Date(System.currentTimeMillis()).getTime());
		boolean result = server.addDeviceInfo(entity);
		int res = result ? Constant.RESPONSE_OK : Constant.RESPONSE_ERR;
		Gson gson = new Gson();
		return gson.toJson(res);
	}
	
	@RequestMapping(value = "/batchAdd.lt")
	@ResponseBody
	public String batchAdd(@RequestParam MultipartFile file) {
		boolean result = false;
		List<DeviceInfo> list = null;
		try {
			list = officeService.getDeviceInfos(file.getInputStream());
			server.saveBatch(list);
//			for(int i = 0;i<list.size();i++){
//				logger.info(i+" info:{}",list.get(i) == null?null:list.get(i).toString());
//			}
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		int res = result ? Constant.RESPONSE_OK : Constant.RESPONSE_ERR;
		Gson gson = new Gson();
		return gson.toJson(res);
	}

	@RequestMapping(value = "/updateDevice.lt")
	@ResponseBody
	public String updateDevice(HttpServletRequest request, HttpServletResponse response)
			throws UnsupportedEncodingException {
		int id = Integer.parseInt(ToolKits.getRequestParamValue(request, "id"));
		String deviceNo = ToolKits.getRequestParamValue(request, "device_no");
		String phoneNumber = ToolKits.getRequestParamValue(request, "phone_number");
		String simNo = ToolKits.getRequestParamValue(request, "sim_no");
		String deviceDesc = ToolKits.getRequestParamValue(request, "device_desc");
		DeviceInfo entity = new DeviceInfo(deviceNo, phoneNumber, simNo, deviceDesc);
		entity.setId(id);
		entity.setUpdate_date(new Date(System.currentTimeMillis()).getTime());
		boolean result = server.updateDeviceInfo(entity);

		int res = result ? Constant.RESPONSE_OK : Constant.RESPONSE_ERR;
		Gson gson = new Gson();
		return gson.toJson(res);
	}

	@RequestMapping(value = "/listDeviceInfo.lt")
	@ResponseBody
	public String listDevicesInfo() {
		List<DeviceInfo> list = server.listDeviceInfo();
		Gson gson = new Gson();
		return gson.toJson(list);
	}

	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/listDevicesInfoPaging.lt")
	@ResponseBody
	public String listDevicesInfoPaging(HttpServletRequest request, HttpServletResponse response) {

		String device_no = ToolKits.getRequestParamValue(request, "device_no");
		int status = ToolKits.getRequestParamValueForInt(request, "status");
		int charge = ToolKits.getRequestParamValueForInt(request, "charge");
		int battery1 = ToolKits.getRequestParamValueForInt(request, "battery1");
		int battery2 = ToolKits.getRequestParamValueForInt(request, "battery2");
		int firmware = ToolKits.getRequestParamValueForInt(request, "firmware");
		int hdware = ToolKits.getRequestParamValueForInt(request, "hdware");
		String time1 = ToolKits.getRequestParamValue(request, "time1");
		String time2 = ToolKits.getRequestParamValue(request, "time2");
		int falut = ToolKits.getRequestParamValueForInt(request, "falut");

		long updateTime1 = time1 == null ? -1 : ToolKits.date2Long(time1);
		long updateTime2 = time2 == null ? -1 : ToolKits.date2Long(time2);

		int pageNo = 1;
		int pageSize = Constant.PAGE_SIZE;
		try {
			pageNo = ToolKits.getRequestParamValueForInt(request, "page_no");
			pageSize = ToolKits.getRequestParamValueForInt(request, "page_size");
		} catch (Exception e) {
			pageSize = Constant.PAGE_SIZE;
			pageNo = 1;
		}
		if (pageNo <= 0) {
			pageNo = 1;
		}

		if (pageSize <= 0) {
			pageSize = Constant.PAGE_SIZE;
		}

		int start = (pageNo - 1) * pageSize;
		int end = pageSize;
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("device_no", device_no);
		params.put("status", status);
		params.put("charge", charge);
		params.put("battery1", battery1);
		params.put("battery2", battery2);
		params.put("firmware",firmware);
		params.put("hdware",hdware);
		params.put("updateTime1", updateTime1);
		params.put("updateTime2", updateTime2);
		params.put("falut", falut);
		params.put("start", start);
		params.put("end", end);
		List<DeviceInfo> list = server.listDeviceInfoPaging(params);
		PageInfo<List> plist = new PageInfo<List>(server.totals(params), list);
		plist.setPageNo(pageNo);
		plist.setPageSize(pageSize);
		plist.setPagesSize(plist.pagesSize());
		Gson gson = new Gson();
		return gson.toJson(plist);
	}

	@RequestMapping(value = "/removeDevice.lt")
	@ResponseBody
	public String removeDevicesInfo(HttpServletRequest request, HttpServletResponse response) {
		boolean result = false;
		String device_no = ToolKits.getRequestParamValue(request, "device_no");
		DeviceInfo entity = server.getDeviceInfoByDeviceNo(device_no);
		if (entity != null)
			result = server.removeDeviceInfo(entity);

		int res = result ? Constant.RESPONSE_OK : Constant.RESPONSE_ERR;
		Gson gson = new Gson();
		return gson.toJson(res);
	}

	@RequestMapping(value = "/showDeviceDetails.lt")
	public String showDevicesInfoDetails(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		int id = Integer.parseInt(ToolKits.getRequestParamValue(request, "id"));
		DeviceInfo entity = server.getDeviceInfoById(id);
		map.put("entity", entity);
		return "/WEB-INF/device/deviceDetails";
	}

	@RequestMapping(value = "/getDeviceInfoById.lt")
	@ResponseBody
	public String getDeviceInfoById(HttpServletRequest request, HttpServletResponse response) {
		int id = ToolKits.getRequestParamValueForInt(request, "id");
		DeviceInfo entity = server.getDeviceInfoById(id);
		Gson gson = new Gson();
		if (entity != null)
			return gson.toJson(entity);

		int res = Constant.RESPONSE_ERR;

		return gson.toJson(res);
	}

	@RequestMapping(value = "/matchingDeviceNo.lt")
	@ResponseBody
	public String matchingDeviceNo(HttpServletRequest request, HttpServletResponse response) {
		String device_no = ToolKits.getRequestParamValue(request, "device_no");
		List<String> entity = server.matchingDeviceNo(device_no);
		Gson gson = new Gson();
		if (entity != null)
			return gson.toJson(entity);

		int res = Constant.RESPONSE_ERR;

		return gson.toJson(res);
	}

	@RequestMapping(value = "/unlock.lt")
	@ResponseBody
	public String unlock(HttpServletRequest request, HttpServletResponse response) {
		boolean result = false;
		String deviceId = ToolKits.getRequestParamValue(request, "deviceid");
		DeviceInfo device = server.getDeviceInfoByDeviceNo(deviceId);

		if (device != null)
			try {
				String content = CommandUtil.getUnlockCommand();
				device = server.unLockDeviceBySMS(device, content);
				if (null == device) {
					result = false;
				} else if (device.getStatus() != 2) {
					result = false;
				} else if (device.getStatus() == 2) {
					result = true;
				}
			} catch (InterruptedException | ExecutionException e) {
				
				e.printStackTrace();
				result = false;
			}

		Gson gson = new Gson();
		int res = result ? Constant.RESPONSE_OK : Constant.RESPONSE_ERR;
		return gson.toJson(res);
	}

	@RequestMapping(value = "/refresh.lt")
	@ResponseBody
	public String refresh(HttpServletRequest request, HttpServletResponse response) {
		String deviceId = ToolKits.getRequestParamValue(request, "deviceid");
		DeviceInfo device = new DeviceInfo();
		device.setDevice_no(deviceId);
		try {
			device = server.refreshDevice(device);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Gson gson = new Gson();
		return gson.toJson(device);
	}

	@RequestMapping(value = "/control.lt")
	@ResponseBody
	public String control(HttpServletRequest request, HttpServletResponse response) {
		boolean result = false;
		String number = ToolKits.getRequestParamValue(request, "phonenumber");
		String content = ToolKits.getRequestParamValue(request, "command");
		DeviceInfo device = server.getDeviceInfoByPhoneNumber(number);
		// device.setDevice_no(deviceId);
		if (device != null && !ToolKits.isEmpty(content))
			try {
				logger.warn("do action:{}", content);
				device = server.unLockDeviceBySMS(device, content);
				if (null == device) {
					result = false;
				} else if (device.getStatus() != 2) {
					result = false;
				} else if (device.getStatus() == 2) {
					result = true;
				}
			} catch (InterruptedException | ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				result = false;
			}

		Gson gson = new Gson();
		int res = result ? Constant.RESPONSE_OK : Constant.RESPONSE_ERR;
		return gson.toJson(res);
	}

}
